#!/bin/bash

### PROGRAM NAME
PROGRAM=${0##*/}

### configuration vars
tempsave=$$_flickr_com.tmp.tmp
savefile=save-flickr2.html
cookie_repo=cookie_flickr.txt
cache_dir=cache

# whether get original image link
opt_original=0
opt_mode_str=Quick
# whether delete temp save file
opt_deltmp=1
# whether INPUT is URL
opt_isurl=0
# whether INPUT is from clipboard
opt_clipboard=0
# image border style text
opt_border_style=

### usage (help screen)
usage() {
    cat <<EO_ECHO 1>&2
USAGE
    $PROGRAM [OPTIONS] [INPUT]
INPUT
    If <INPUT> is omitted, Windows clipboard will be used,
    Other wise INPUT is a filename or a URL
THE CONTENT OF <INPUT>
    The content is either from Windows clipboard, or from command line argument
    <INPUT>. If <INPUT> begins with 'http://', it is assumed as a URL, and the
    script tries to get the page from the Internet before parsing.
OPTIONS
    -o, --original       Get original image links, this option overrides '-q'
                         WARNING: this will result in getting detail pages
                         for each image from the Flickr website (Original Mode)
    -q, --quick          Quickly get the image links from set index page
                         (the default behavior, i.e., Quick Mode)
    -O, --output=FILE    Set the output file, default is '${savefile}'
    -c, --cookie=FILE    Set the cookie file, default is '${cookie_repo}'
    -h, --help           This help screen
EO_ECHO
    exit 1
}

### getopts
## options parsing
parsed=$(getopt --shell bash --name ${0##*/} \
    --options okqhbc: \
    --longoptions original,keep-temp,quick,help,img-border,cookie: \
    -- "$@")
eval set -- "$parsed"
if [[ $? -ne 0 ]]; then
    echo "Error parsing options, quit..." 1>&2
    exit 1
fi
while true; do
    case "$1" in
        -h|--help)
        usage
        ;;
        -k|--keep-temp)
        opt_deltmp=0
        shift 1
        ;;
        -q|--quick)
        opt_original=0
        opt_mode_str=Quick
        shift 1
        ;;
        -o|--original)
        opt_original=1
        opt_mode_str=Original
        shift 1
        ;;
        -b|--img-border)
        opt_border_style='style="border: 2px solid #CCC;" '
        shift 1
        ;;
        -O|--output)
        savefile=$2
        shift 2
        ;;
        --)
        shift
        break
        ;;
        *)
        echo "ERROR: unknown option: '$arg'" 1>&2
        echo "Try run the script with argument \`-h' or \`--help'" 1>&2
        exit 2
        ;;
    esac
done

### INPUT
if [[ -z "$1" ]]; then # INPUT is not at the command line
    opt_input=$(getclip)
    opt_clipboard=1
else
    opt_input=$1
    opt_clipboard=0
fi
opt_isurl=$(echo $opt_input | grep -c -i '^[\t ]*http://')
echo "<<<  $opt_mode_str Mode  >>>"
### If INPUT is a URL, then get content from internet
if (( "$opt_isurl" == 1 )); then
    echo Getting content from web...
    echo $opt_input | sed -e "s|^[\t ]*||" | wget -O"$tempsave" -i-
### ElseIf INPUT is from command line, then treat it as input file name
elif (( "$opt_clipboard" == 0 )); then
    tempsave=$opt_input
else # Otherwise, it is from clipboard and not a URL, so it is the HTML source
    echo Getting content from clipboard...
    echo $opt_input | unix2dos >$tempsave
fi

### environment assuring
if [[ ! -f $cookie_repo ]]; then echo "ERROR: cookie file '$cookie_repo' not exists" 1>&2; exit; fi
if [[ ! -d $cache_dir ]]; then mkdir $cache_dir; fi
curdate=$(date)
echo "Source content temp: $tempsave"
echo "Target save file   : $savefile"

cat >$savefile <<EOF
<!-- IMAGE LIST BEGIN: Flickr.com images HTML source by $PROGRAM, $opt_mode_str Mode, date: $curdate -->

EOF

count=0
if (( $opt_original > 0 )); then ### original mode
    # <a href="/photos/xiazuoling/3798312442/in/set-72157621971239534/" title="IMG_0661" class="image_link">
    grep -ihoP '<a\s*href="[[:alnum:]/.-]+\d+/in/set-\d+/"\s*title="[^"]+"\s*class="image_link"' $tempsave |
        sed -e '1d' |
        while read line; do
            oimgurl=$(echo $line | grep -ihoP '(?<=href=")[^"]+(?=")' |
                sed -e 's|/in/set-|/sizes/o/in/set-|' -e 's|^|http://www.flickr.com|')
            imgtitle=$(echo $line | grep -ihoP '(?<=title=")[^"]+(?=")')
            imgid=$(echo $oimgurl | gawk -F/ '{print $6;}')
            let ++count
            count_fmt=$(printf '%02d' $count)
            printf '\n%02d: %s / %s\n    %s\n' $count "$imgtitle" "$imgid" "$oimgurl"
            opagesave=${cache_dir}/${imgid}.opage
            if [[ ! -f ${opagesave} ]]; then
                wget --referer="http://www.flickr.com/photos/xiazuoling/" \
                --user-agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)" \
                --load-cookie=$cookie_repo \
                -O${opagesave} $oimgurl;
                echo Original image page saved: ${opagesave}
            fi
            # Original image URL assumption:
            #<p><img src="http://farm3.static.flickr.com/2427/3797497449_23aea1cf4d_o.jpg" /><br /></p>
            #<p><img src="http://farm3.static.flickr.com/2605/3797494369_6f8f9bdefd_b.jpg" /><br /></p>
            if opage_html=$(grep -i -A2 'copy and paste this html' "$opagesave" | sed -e '1d' | grep -ihoP '<a\s+.+?</a>')
            then
                # <a href="http://www.flickr.com/photos/xiazuoling/4012720247/" title="IMG_4690 by Xia Zuoling, on Flickr"><img src="http://farm3.static.flickr.com/2560/4012720247_752c28c36a_o.jpg" width="480" height="640" alt="IMG_4690" /></a>
                #echo \$opage_html: $opage_html
                src_a_href=$(echo "$opage_html" | grep -ihoP '(?<=href=")[^"]+')
                src_a_title=$(echo "$opage_html" | grep -ihoP '(?<=[< ]title=")[^"]+')", ID $imgid"
                src_img_url=$(echo "$opage_html" | grep -ihoP '(?<=[< ]src=")[^"]+')
                #src_img_width=$(echo "$opage_html" | grep -ihoP '(?<=[< ]width=")[^"]+')
                #src_img_height=$(echo "$opage_html" | grep -ihoP '(?<=[< ]height=")[^"]+')
                # printf: img_src, img_alt, border_style, a_href, a_alt, a_title, IMG_NO
                printf "<img src=\"%s\" alt=\"%s\" %s/><br />&uarr;<a href=\"%s\" title=\"%s\" target=\"_blank\">IMG#%02d</a>&nbsp;\n\n" \
                    "$src_img_url" "$src_a_title" "$opt_border_style" "$src_a_href" "$src_a_title" $count >>$savefile
            else
                echo "ERROR: original image URL not matched!"
                sleep 1
            fi
        done
    # //grep [image detail page]
else ### quick mode
    sed -n -e '/div.id="setThumbs"/,/div.id="vsPagination"/p' "$tempsave"  | grep -ihoP '<a[^<]+><img[^>]+/></a>' |
    while read line; do
        img_id=$(echo "$line" | grep -ihoP '/photos/[^/]+/\d+/in/' | grep -ihoP '\d+(?=/in/)')
        img_page_url="http://www.flickr.com"$(echo $line | grep -ihoP '(?<=a.href=")[^"]+')
        img_url=$(echo "$line" | grep -ihoP '(?<=img.src=")[^"]+' | sed -e 's|_.\.jpg|.jpg|')
        img_title=$(echo "$line" | grep -ihoP '(?<=title=")[^"]+' | sed -e 's|.*|&, on Flickr|')", ID $img_id"
        let count++
        printf '\n%02d: %s\n    %s\n' $count "$img_title" "$img_url"
        printf '<img src="%s" alt="%s" %s/><br />&uarr;<a href="%s" title="%s" target="_blank">IMG#%02d</a>&nbsp;\n\n' \
            "$img_url" "$img_title" "$opt_border_style" "$img_page_url" "$img_title" $count >>$savefile
    done
fi

# ending
if (( $opt_deltmp > 0 )); then rm -f "$tempsave"; fi

cat >>$savefile <<EOF
<!-- IMAGE LIST END: by $PROGRAM -->

EOF

exit 0
